<?php
namespace App\Task;

use Hyperf\DbConnection\Db;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Crontab\Annotation\Crontab;

/**
 * @Crontab(
 *     rule="0 0 1 1 *",
 *     name="AutoGetBlog",
 *     callback="execute",
 *     memo="每年1月1日执行一次"
 * )
 */
class AutoGetIrugbyshop
{
    protected $logger;


    public function __construct(LoggerFactory $loggerFactory)
    {
        $this->logger = $loggerFactory->get('tasklog', 'tasklog');
    }

    public function execute()
    {
        try {
            $webname = 'irugbyshop';

            $stock_status = [
                7 => "In Stock",
                8 => "Pre-Order",
                5 => "Out Of Stock",
                6 => "2-3 Days",
            ];

            $maxProduct = Db::table('products')
                ->where('webname', $webname)
                ->orderBy('product_id', 'desc')
                ->first();
            if (!$maxProduct) {
                $maxProductId = 0;
            }else{
                $maxProductId = $maxProduct->product_id;
            }

            $conn = Db::connection($webname);

            $products = $conn->cursor("SELECT
                    p.product_id,p.model,p.sku,p.upc,p.ean,p.jan,p.isbn,p.mpn,p.location,p.quantity,p.stock_status_id,p.image,p.manufacturer_id,p.shipping,p.price,p.points,p.tax_class_id,p.date_available,p.weight,p.weight_class_id,p.length,p.width,p.height,p.length_class_id,p.subtract,p.minimum,p.sort_order,p.status,
                    pd.name AS product_name, pd.description, pd.tag, pd.meta_title, pd.meta_description, pd.meta_keyword,
                    ps.price as special_price,
                    sc.image_src as size_chart
                FROM oc_product p
                JOIN oc_product_description pd ON p.product_id = pd.product_id
                JOIN oc_product_special ps ON p.product_id = ps.product_id
                JOIN oc_size_chart sc ON p.product_id = sc.product_id
                WHERE p.product_id > ?
                ORDER BY p.product_id ASC
                LIMIT 12", [$maxProductId]);

            if (!$products->valid()) {
                $this->logger->info("irugbyshop：没有数据", ['irugbyshop']);
                return false;
            }

            $categorys = $conn->cursor("SELECT
                    pta.product_id,
                    pta.category_id,
                    pta.main_category,
                    cd.category_id,
                    cd.name
                FROM oc_product_to_category pta
                JOIN oc_category_description cd ON pta.category_id = cd.category_id");

            // 查询商品属性信息
            $options = $conn->cursor("SELECT
                po.product_id,
                po.product_option_id,
                po.option_id,
                od.name AS option_name,
                po.value AS option_value,
                po.required,
                pov.product_option_value_id,
                pov.option_value_id,
                ovd.name AS option_value_name,
                pov.quantity,
                pov.subtract,
                pov.price,
                pov.price_prefix,
                pov.points,
                pov.points_prefix,
                pov.weight,
                pov.weight_prefix
            FROM oc_product_option po
            LEFT JOIN oc_option_description od ON po.option_id = od.option_id
            LEFT JOIN oc_product_option_value pov ON po.product_option_id = pov.product_option_id
            LEFT JOIN oc_option_value_description ovd ON (pov.option_value_id = ovd.option_value_id AND pov.option_id = ovd.option_id)
            WHERE od.language_id = 1 AND ovd.language_id = 1");

            //图片
            $images = $conn->cursor("SELECT product_image_id,product_id,image
                FROM oc_product_image
                ORDER BY sort_order ASC");

            $products_arr = $categoryMap = $optionMap = $imagesMap = $products_ids = [];

            //分类
            foreach ($categorys as $category) {
                $productId = $category->product_id;
                if (!isset($categoryMap[$productId])) {
                    $categoryMap[$productId] = [];
                }
                $categoryMap[$productId][] = [
                    'category_id' => $category->category_id,
                    'name' => $category->name,
                    'main_category' => $category->main_category,
                ];
            }

            //属性
            foreach ($options as $option) {
                $productId = $option->product_id;
                if (!isset($optionMap[$productId])) {
                    $optionMap[$productId] = [];
                }

                // 组织选项结构
                if (!isset($optionMap[$productId][$option->option_id])) {
                    $optionMap[$productId][$option->option_id] = [
                        'option_id' => $option->option_id,
                        'name' => $option->option_name,
                        'value' => $option->option_value,
                        'required' => $option->required,
                        'values' => []
                    ];
                }

                // 添加选项值
                if ($option->product_option_value_id) {
                    $optionMap[$productId][$option->option_id]['values'][] = [
                        'product_option_value_id' => $option->product_option_value_id,
                        'option_value_id' => $option->option_value_id,
                        'name' => $option->option_value_name,
                        'quantity' => $option->quantity,
                        'subtract' => $option->subtract,
                        'price' => $option->price,
                        'price_prefix' => $option->price_prefix,
                        'points' => $option->points,
                        'points_prefix' => $option->points_prefix,
                        'weight' => $option->weight,
                        'weight_prefix' => $option->weight_prefix
                    ];
                }
            }

            //图片
            foreach ($images as $image) {
                $productId = $image->product_id;
                if (!isset($imagesMap[$productId])) {
                    $imagesMap[$productId] = [];
                }
                $imagesMap[$productId][] = $image->image;
            }

            foreach ($products as $product) {
                $product->stock_status_val = isset($stock_status[$product->stock_status_id]) ? $stock_status[$product->stock_status_id] : 'Unknown';

                $product->categories = $categoryMap[$product->product_id] ?? [];

                $product->images = $imagesMap[$product->product_id] ?? [];

                $productOptions = $optionMap[$product->product_id] ?? [];
                $product->options = array_values($productOptions);

                $products_arr[] = $product;
            }

            // 3. 将新数据写入products表
            $insertData = [];
            foreach ($products_arr as $product) {
                $insertData[] = [
                    'product_id' => $product->product_id,
                    'webname' => $webname,
                    'date_added' => json_encode($product),
                    'status' => 1,
                    'add_time' => date('Y-m-d H:i:s'),
                ];

                $products_ids[] = $product->product_id;
            }

            if (!empty($insertData)) {
                Db::table('products')->insert($insertData);
            }

            $this->logger->info("irugbyshop 数据", $products_ids);
        } catch (\InvalidArgumentException $e) {
            $this->logger->error("数据库配置错误", [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
        } catch (\PDOException $e) {
            $this->logger->error("数据库连接失败", [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
        } catch (\Throwable $e) {
            $this->logger->error("系统错误", [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
        }
    }
}
